<?php

namespace app\admin\model\agent;

use app\common\library\Sms;
use Exception;
use think\Db;
use think\Log;
use think\Model;


class Order extends Model
{





    // 表名
    protected $name = 'user_agent';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'payTime_text'
    ];






    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['payTime']) ? $data['payTime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * 创建订单
     */
    public static function addOrder($user,$agentId)
    {
        $info = \app\admin\model\agent\Agent::where('id',$agentId)->where('status',1)->find();
        if(empty($info)){
            throw new \think\Exception("代理等级信息获取失败");
        }
        if($user->agent>0){
            $oldInfo = \app\admin\model\agent\Agent::where('id',$user->agent)->where('status',1)->find();
            if(!empty($oldInfo)){
                $info['price'] = $info['price']>$oldInfo['price']?bcsub($info['price'],$oldInfo['price'],2):$info['price'];
            }
        }
        $data = array(
            "uid"=>$user->id,
            "agent"=>$agentId,
            "title"=>$info['title'],
            "payPrice"=>$info['price'],
            "payType"=>"none",
            "createtime"=>time(),
        );
        $newId = self::insert($data,false,1);
        if(empty($newId)){
            throw new \think\Exception("订单创建失败，请重试");
        }
        $orderId = \fast\Utils::getOrderId("agent",$newId);
        self::where('id',$newId)->update(['orderId'=>$orderId,'updatetime'=>time()]);
        return $orderId;
    }
    /**
     * 订单支付成功
     */
    public static function agentPay($orderId,$transaction_id,$payType)
    {
        Db::startTrans();
        try {
            $re = self::where('orderId', $orderId)->where('payStatus', 0)->update([
                "payType" => $payType,
                "payTime" => time(),
                "payStatus" => 1,
                "transaction_id" => $transaction_id,
                "orderStatus" => 2,
            ]);
            if ($re == false) {
                throw new \think\Exception("订单更新失败");
            }
            $order = self::where('orderId', $orderId)->find();
            $user = \app\admin\model\User::where('id', $order['uid'])->find();
            $isPay = 0;
            if ($user['agent'] == 0) {
                $isPay = 1;
            }
            if ($user['agent'] < $order['agent']) {
                $user->save(['agent' => $order['agent']]);
            }
            $relation = explode("-", $user['relation']);
            $agent = \app\admin\model\agent\Agent::where('id', $order['agent'])->find();
            if ($relation[0] > 0) {
                foreach ($relation as $ks => $vs) {
                    $level = $ks + 1;
                    if ($vs <= 0) {
                        continue;
                    }
                    $upUser = \app\admin\model\User::where('id', $vs)->where('agent', '>', 0)->find();
                    if (empty($upUser)) {
                        continue;
                    }
                    if ($isPay == 1) {
                        $price = bcmul($order['payPrice'], 50 * 0.01, 2);
                    } else {
                        $price = bcmul($order['payPrice'], $agent['agent'] * 0.01, 2);
                    }
                    if ($price > 0) {
                        \app\admin\model\rebate\Rebate::saveRebateInfo([
                            "uid" => $vs,
                            "disUid" => $user['id'],
                            "orderId" => $orderId,
                            "level" => $level,
                            "type" => 5,
                            "percent" => $agent['agent'],
                            "price" => $price,
                            "info" => '会员升级代理',
                        ]);
                        Sms::otherSend([
                            "uid"=>$vs,
                            "type"=>3,
                            "mobile"=>substr($user['mobile'], 7,4),
                            "level"=>$level,
                            "payPrice"=>$order['payPrice'],
                            "title"=>$order['title'],
                            "price"=>$price,
                        ]);
                        break;
                    }
                }
            }
        }catch (\think\Exception $exception){
            Log::error($exception->getMessage());
            Db::rollback();
        }
        Db::commit();
        return true;
    }
}
